//
//  AppDelegate.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/19.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.rootViewController = defaultController()
//        window?.rootViewController = CNBaseInputViewController()
        
        window?.makeKeyAndVisible()
//        CNSQLiteManager.sharedManager
        return true
    }
    
    // 切换控制器
    class func loadViewController(controller: UIViewController) {
        
        let appDelegate = UIApplication.sharedApplication().delegate
        appDelegate?.window??.rootViewController = controller
    }
    
    // 判断要加载的控制器
    private func defaultController() ->UIViewController {
        
        if CNUserAccountViewModel.sharedInstance.isLogin {
            
            return isNewVersion() ? CNNewFeatureViewController() : CNWelcomeViewController()
        } else {
            
            return CNMainViewController()
        }
    }
    
    // 是否为新版本
    private func isNewVersion() -> Bool {
        
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        let sandboxVersion = NSUserDefaults.standardUserDefaults().stringForKey(sandboxVersionKey)
        let newVersion = currentVersion != sandboxVersion
        if newVersion {
            
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: sandboxVersionKey)
            // iOS8以后不需要同步
            NSUserDefaults.standardUserDefaults().synchronize()
        }
        return newVersion
    }
    
    // 设置全局导航栏皮肤
    private func setupAppearance() {
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UIBarButtonItem.appearance().tintColor = UIColor.orangeColor()
    }

    func applicationDidEnterBackground(application: UIApplication) {
        CNStatusDAL.sharedDAL.clearData()
    }
}

